import axios from "axios";
import type {
	AxiosInstance,
	AxiosRequestConfig,
	AxiosResponse,
	AxiosError,
	InternalAxiosRequestConfig,
} from "axios";
import { showMessage } from "./status";
import { IResponse } from "./type";
import { TokenPrefix, getToken } from "@/utils/auth";
import { ElMessage } from "element-plus";
const service: AxiosInstance = axios.create({
	baseURL:
		import.meta.env.MODE === "development"
			? import.meta.env.VITE_APP_API_BASEURL
			: BASE_CONFIG.baseURL,
	timeout: 0,
});

// axios实例拦截请求
service.interceptors.request.use(
	(config: InternalAxiosRequestConfig) => {
		const token = getToken();
		if (token) {
			config.headers.Authorization = `${TokenPrefix}${token}`;
		}
		return config;
	},
	(error: AxiosError) => {
		return Promise.reject(error);
	}
);

// axios实例拦截响应
service.interceptors.response.use(
	(response: AxiosResponse) => {
		if (response.status === 200) {
			return response;
		}
		showMessage(response.status);
		return response;
	},
	// 请求失败
	(error: any) => {
		const { response } = error;
		if (response) {
			// 请求已发出，但是不在2xx的范围
			showMessage(response.status);
			return Promise.reject(response.data);
		}
		showMessage("网络连接异常,请稍后再试!");
	}
);

const request = <T = any>(config: AxiosRequestConfig): Promise<T> => {
	const conf = config;
	return new Promise((resolve) => {
		service.request<any, AxiosResponse<IResponse>>(conf).then((res: AxiosResponse<IResponse>) => {
			const { data } = res;
			if (data.code !== 200) {
				ElMessage.error(data.msg);
			}
			resolve(data as T);
		});
	});
};
export function get<T = any>(config: AxiosRequestConfig): Promise<T> {
	return request({ ...config, method: "GET" });
}
export function del<T = any>(config: AxiosRequestConfig): Promise<T> {
	return request({ ...config, method: "DELETE" });
}
export function post<T = any>(config: AxiosRequestConfig): Promise<T> {
	return request({ ...config, method: "POST" });
}
export function put<T = any>(config: AxiosRequestConfig): Promise<T> {
	return request({ ...config, method: "PUT" });
}

// export function download(config: AxiosRequestConfig): void {
// 	service({
// 		...config,
// 		method: "GET",
// 		responseType: "blob",
// 	})
// 		.then((res) => {
// 			const blob = new Blob([res.data]);
// 			const fileName = res.headers["content-disposition"].split(";")[1].split("filename=")[1]; // 从响应头中获取文件名
// 			const downloadUrl = window.URL.createObjectURL(blob); // 创建下载链接
// 			const link = document.createElement("a");
// 			link.href = downloadUrl;
// 			link.setAttribute("download", decodeURIComponent(fileName)); // 设置下载的文件名
// 			document.body.appendChild(link);
// 			link.click();
// 			document.body.removeChild(link);
// 		})
// 		.catch((e) => {
// 			ElMessage.error("下载失败，请联系管理员！");
// 		});
// }

//返回promise版本
export function download(config: AxiosRequestConfig): Promise<void> {
	return service({
		...config,
		method: "GET",
		responseType: "blob",
		onDownloadProgress: config.onDownloadProgress,
	})
		.then((res) => {
			const blob = new Blob([res.data]);
			const fileName = res.headers["content-disposition"]
				.split(";")[1]
				.split("filename=")[1]
				.trim(); // 添加了 trim() 来清理可能的空白字符
			const downloadUrl = window.URL.createObjectURL(blob);
			const link = document.createElement("a");
			link.href = downloadUrl;
			link.setAttribute("download", decodeURIComponent(fileName));
			document.body.appendChild(link);
			link.click();
			document.body.removeChild(link);
			window.URL.revokeObjectURL(downloadUrl); // 清理创建的 URL，避免内存泄漏
		})
		.catch((e) => {
			ElMessage.error("下载失败，请联系管理员！");
			throw e; // 重新抛出错误，以便在调用处可以捕获
		});
}
export default request;

export type { AxiosInstance, AxiosResponse };
